package org.chen.wordwave.act;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.activity.OnBackPressedCallback;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;

import com.blankj.utilcode.util.ActivityUtils;
import com.hjq.toast.Toaster;

import org.chen.wordwave.R;
import org.chen.wordwave.base.BaseActivity;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.fragment.AboutMeFragment;
import org.chen.wordwave.fragment.DakaFragment;
import org.chen.wordwave.fragment.SouYeFragment;
import org.chen.wordwave.fragment.WordsFragment;
import org.chen.wordwave.init.WordInit;
import org.chen.wordwave.tools.user.UserUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class Main extends BaseActivity {
    public static final int[] iconArray = {
            R.mipmap.ji_10,
            R.mipmap.ji_50,
            R.mipmap.ji_100,
            R.mipmap.quan8,
            R.mipmap.tanks1,
            R.mipmap.ji_400,
            R.mipmap.ji_500,
            R.mipmap.thanks2
    };
    private static final int SOUYE_FRAGMENT = 111;
    private static final int WORDS_FRAGMENT = 222;
    private static final int DAKA_FRAGMENT = 333;
    private static final int ABOUT_ME_FRAGMENT = 444;
    private static final int WANGT_EXIT = 555;
    private int nowChecked = 0;
    private SouYeFragment souYeFragment;
    private WordsFragment wordsFragment;
    private DakaFragment dakaFragment;
    private AboutMeFragment aboutMeFragment;
    private LinearLayout ll_shouye, ll_danci, ll_daka, ll_wode;
    private FragmentTransaction fragmentTransaction;
    private boolean isExit = false;
    private Handler handler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == WANGT_EXIT) {
                isExit = false;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handleOnBackPressed();

        // 初始化版本管理器
        VersionManager versionManager = new VersionManager(this);
        // 应用启动后静默检查更新
        versionManager.checkUpdateSilently();
    }

    @Override
    public Integer getLayoutResId() {
        return R.layout.main_act;
    }

    @Override
    public void init() {
        ll_shouye = findViewById(R.id.ll_shouye);
        ll_danci = findViewById(R.id.ll_danci);
        ll_daka = findViewById(R.id.ll_daka);
        ll_wode = findViewById(R.id.ll_wode);
        ll_shouye.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkBar(SOUYE_FRAGMENT);
            }
        });

        ll_danci.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkBar(WORDS_FRAGMENT);
            }
        });

        ll_daka.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (WordInit.userInfo.getEmail() == null){
                    Toaster.show(getString(R.string.need_login));
                    showLoginDialog();
                }else {
                    checkBar(DAKA_FRAGMENT);
                }
            }
        });

        ll_wode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (WordInit.userInfo.getEmail() == null){
                    Toaster.show(getString(R.string.need_login));
                    showLoginDialog();
                }else {
                    checkBar(ABOUT_ME_FRAGMENT);
                }
            }
        });

        checkBar(SOUYE_FRAGMENT);
        if (WordInit.userInfo.getEmail() != null){
            System.out.println(WordInit.userInfo);
            checkMembershipStatus();
        }
    }
    private void checkBar(int i) {
        if (nowChecked == i) {
            return;
        }
        setAllNotChecked();
        fragmentTransaction = getSupportFragmentManager().beginTransaction();
        hideAllFragment();

        switch (i) {
            case SOUYE_FRAGMENT:
                ll_shouye.setSelected(true);
                if (souYeFragment == null) {
                    souYeFragment = new SouYeFragment();
                    fragmentTransaction.add(R.id.fl_main, souYeFragment);
                }
                fragmentTransaction.show(souYeFragment);
                break;
            case WORDS_FRAGMENT:
                ll_danci.setSelected(true);
                if (wordsFragment == null) {
                    wordsFragment = new WordsFragment();
                    fragmentTransaction.add(R.id.fl_main, wordsFragment);
                }
                fragmentTransaction.show(wordsFragment);
                break;
            case DAKA_FRAGMENT:
                ll_daka.setSelected(true);
                if (dakaFragment == null) {
                    dakaFragment = new DakaFragment();
                    fragmentTransaction.add(R.id.fl_main, dakaFragment);
                }
                fragmentTransaction.show(dakaFragment);
                break;
            case ABOUT_ME_FRAGMENT:
                ll_wode.setSelected(true);
                if (aboutMeFragment == null) {
                    aboutMeFragment = new AboutMeFragment();
                    fragmentTransaction.add(R.id.fl_main, aboutMeFragment);
                }
                fragmentTransaction.show(aboutMeFragment);
                break;
            default:
                Toast.makeText(this, R.string.app_error, Toast.LENGTH_SHORT).show();
                break;
        }

        fragmentTransaction.commit();
        nowChecked = i;
    }

    private void showLoginDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.login_title);
        builder.setMessage(R.string.login_message);
        builder.setPositiveButton(R.string.login_btn, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent intent = new Intent(Main.this, Login.class);
                startActivity(intent);
            }
        }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private void hideAllFragment() {
        if (souYeFragment != null) {
            fragmentTransaction.hide(souYeFragment);
        }

        if (wordsFragment != null) {
            fragmentTransaction.hide(wordsFragment);
        }

        if (dakaFragment != null) {
            fragmentTransaction.hide(dakaFragment);
        }

        if (aboutMeFragment != null) {
            fragmentTransaction.hide(aboutMeFragment);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 结束之前的所有activity
        ActivityUtils.finishAllActivitiesExceptNewest();
    }

    private void setAllNotChecked() {
        ll_shouye.setSelected(false);
        ll_danci.setSelected(false);
        ll_daka.setSelected(false);
        ll_wode.setSelected(false);
    }

    private void handleOnBackPressed() {
        OnBackPressedCallback callback = new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                if (!isExit) {
                    isExit = true;
                    Toast.makeText(Main.this, R.string.exit_wordmaster, Toast.LENGTH_SHORT).show();
                    handler.sendEmptyMessageDelayed(WANGT_EXIT, 2000);
                } else {
                    finish();
                }
            }
        };
        getOnBackPressedDispatcher().addCallback(this, callback);
    }

    private void checkMembershipStatus() {
        UserInfo currentUser = UserUtils.getCurrentUser(getApplicationContext());
        if (currentUser.isMember() && currentUser.getMembershipExpiryDate() != null) {
            // 检查会员是否过期
            Date currentDate = new Date();
            if (currentDate.after(currentUser.getMembershipExpiryDate())) {
                currentUser.setMember(false);
                currentUser.setMembershipExpiryDate(null);
                currentUser.save();
            }
        }
    }
}

